//
//  MXNewViewItemDetailVC.m
//  MXの衣柜
//
//  Created by 马霄 on 15/8/16.
//  Copyright (c) 2015年 霄 马. All rights reserved.
//
#define WIDTH ([UIScreen mainScreen].bounds.size.width)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height)
#import "MXNewViewItemDetailVC.h"
#import "AFNetworkHandler.h"
#import "MXNewViewItemDetailModel.h"
#import "MXNewViewItemDetailTableViewCell.h"
#import "SDCycleScrollView.h"
#import "MXFindWebViewVC.h"
#import "DataBaseFMDB.h"
#import <ShareSDK/ShareSDK.h>
#import "MBProgressHUD.h"
@interface MXNewViewItemDetailVC ()<UITableViewDataSource, UITableViewDelegate, SDCycleScrollViewDelegate>
@property (nonatomic, retain) UIButton *backButton;

@property (nonatomic, retain) UIButton *collectButton;

@property (nonatomic, retain) NSMutableArray *itemArray;

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) NSArray *urlStringArray;

@property (nonatomic, retain) SDCycleScrollView *cycleScrollView;

@property (nonatomic, retain) UILabel *TmallLabel;

@property (nonatomic, retain) NSString *TmallLinkString;

@property (nonatomic, retain) NSString *tempTitleString;

@property (nonatomic, retain) NSString *imagePath;

@property (nonatomic, retain) NSString *tempUrl;

@property (nonatomic, retain) UIButton *itemCollectButton;

@property (nonatomic, retain) MBProgressHUD *HUD;

@property (nonatomic, retain) UIView *alterView;
@end

@implementation MXNewViewItemDetailVC
- (void)dealloc
{
    [_HUD release];
    [_alterView release];
    [_naviTemp release];
    [_itemCollectButton release];
    [_tempUrl release];
    [_tempTitleString release];
    [_imagePath release];
    [_TmallLinkString release];
    [_TmallLabel release];
    [_priceString release];
    [_cycleScrollView release];
    [_urlStringArray release];
    [_tableView release];
    [_itemArray release];
    [_itemID release];
    [_backButton release];
    [_collectButton release];
    [super dealloc];    
}



-(void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;

}
- (void)viewDidDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.tabBarController.tabBar.hidden = YES;

    
    self.itemArray = [NSMutableArray array];
    self.urlStringArray = [NSArray array];
    
    self.navigationController.navigationBarHidden = YES;
        
    CGFloat topViewHeight = 300;
    
    //网络加载 --- 创建带标题的图片轮播器
    self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, topViewHeight) imageURLStringsGroup:nil]; // 模拟网络延时情景
    self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    self.cycleScrollView.delegate = self;
    self.cycleScrollView.backgroundColor = [UIColor whiteColor];
    //标题的数组
    self.cycleScrollView.placeholderImage = [UIImage imageNamed:@"plaseholder"];
    self.cycleScrollView.dotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
    //    cycleScrollView2.placeholderImage = [UIImage imageNamed:@"placeholder"];
    [self.view addSubview:self.cycleScrollView];
    
    //             --- 模拟加载延迟
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //图片地址的数组
        self.cycleScrollView.imageURLStringsGroup = self.urlStringArray;
    });

    
    [self creatTableView];
    

    [self getData];
    
    [self uiActivityindicatorviewStart];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(uiActivityindicatorviewEnd) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

    // Do any additional setup after loading the view.
}

-(void)uiActivityindicatorviewStart
{
    self.alterView =[[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)] autorelease];
    self.alterView.backgroundColor =[UIColor whiteColor];
    self.HUD = [MBProgressHUD showHUDAddedTo:self.alterView animated:YES];
//    self.HUD.labelText = @"正在努力的给您加载";
    [self.HUD show:YES];
    
    [self.view addSubview:self.alterView];
    
}
-(void)uiActivityindicatorviewEnd
{
    [self.alterView removeFromSuperview];
}

- (void)creatButtons
{
    //后退按钮
    self.backButton  = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.backButton.frame = CGRectMake(WIDTHPRO * 20, HEIGHTPRO * 30, WIDTHPRO * 40, HEIGHTPRO * 40);
    self.backButton.layer.cornerRadius = WIDTHPRO * 20;
    self.backButton.backgroundColor = [UIColor redColor];
    self.backButton.alpha = 0.75;
    [self.backButton setBackgroundImage:[UIImage imageNamed:@"backButton"] forState:(UIControlStateNormal)];
    self.backButton.layer.masksToBounds = YES;
    [self.view addSubview:self.backButton];
    [self.backButton addTarget:self action:@selector(backAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    //收藏按钮
    self.collectButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.collectButton.frame = CGRectMake(WIDTH - WIDTHPRO * 60, HEIGHTPRO * 30, WIDTHPRO * 40, HEIGHTPRO * 40);
    self.collectButton.layer.cornerRadius = WIDTHPRO * 20;
    self.collectButton.backgroundColor = [UIColor redColor];
    self.collectButton.alpha = 0.75;
    [self.collectButton setBackgroundImage:[UIImage imageNamed:@"shareButton"] forState:(UIControlStateNormal)];
    self.collectButton.layer.masksToBounds = YES;
    [self.view addSubview:self.collectButton];
    [self.collectButton addTarget:self action:@selector(collectAction) forControlEvents:(UIControlEventTouchUpInside)];
    
}

- (void)creatTmallLinkButton
{
    self.TmallLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, HEIGHT - HEIGHTPRO * 49, WIDTH, HEIGHTPRO * 49)];
    self.TmallLabel.backgroundColor = [UIColor whiteColor];
    self.TmallLabel.text = @"";
    self.TmallLabel.layer.borderWidth = 1;
    self.TmallLabel.userInteractionEnabled = YES;
    [self.view addSubview:self.TmallLabel];
    [_TmallLabel release];
    
    UIButton *buyButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    buyButton.backgroundColor = [UIColor redColor];
    buyButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [buyButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [buyButton setTitle:@"天猫购买" forState:(UIControlStateNormal)];
    buyButton.frame = CGRectMake(WIDTH - WIDTHPRO  * 120, 0, WIDTHPRO * 80, HEIGHTPRO * 49);
    [buyButton addTarget:self action:@selector(buyAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.TmallLabel addSubview:buyButton];
    
    
    self.itemCollectButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.itemCollectButton setBackgroundImage:[UIImage imageNamed:@"uncollect"] forState:(UIControlStateNormal)];
    [self.itemCollectButton setBackgroundImage:[UIImage imageNamed:@"collected"] forState:(UIControlStateSelected)];
    self.itemCollectButton.frame = CGRectMake( WIDTHPRO * 20, HEIGHTPRO * 4.5, WIDTHPRO * 40, HEIGHTPRO * 40);
    [self.itemCollectButton addTarget:self action:@selector(itemCollectAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.TmallLabel addSubview:self.itemCollectButton];
    
    
    DataBaseFMDB *dbManger = [[[DataBaseFMDB alloc] init] autorelease];
    
    // 创建数据库
    [dbManger createItemDataBase];
    
    // 创建表
        [dbManger creatItemDaseTable];
    
    BOOL exists = [dbManger isItemExists:self.tempTitleString];
    
    if (exists) {
        self.itemCollectButton.selected = YES;
    }

    
    
    
    
    // 隐藏TabBar
    self.tabBarController.tabBar.hidden = YES;
    
}



- (void)creatTableView
{
    
    self.tableView = [[[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:(UITableViewStylePlain)] autorelease];
    self.tableView.delegate = self;
    
    self.tableView.dataSource = self;
    
    self.tableView.tableHeaderView = self.cycleScrollView;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:self.tableView];
}

/*************************** 数据解析部分 *******************************/
- (void)getData
{
    NSString *Path = [NSString stringWithFormat:@"http://hws.m.taobao.com/cache/wdetail/5.0/?id=%@&ttid=201200@taobao_iphone_5.3.1&exParams=%%7B%%22itemId%22%3A%2245722762595%22%%2C%%22ttid%22%3A%%22400000_%%28null%29%40nanren_iphone_6.11%22%2C%%22longitude%22%3A%22121.566902%22%%2C%%22id%22%3A%2245722762595%22%2%C%%22ali_trackid%22%3A%222%3Amm_29983627_0_0%%3A1439701067_2k2_722796056%22%2C%%22sche%22%3A%%22wx6ab5ac17816dfb18%22%2C%%22latitude%22%3A%2238.919613%22%%2C%%22e%22%3A%%22f9QjCcJbJXNw4vFB6t2Z2ueEDrYVVa64yK8Cckff7TVRAdhuF14FMWIcmRsVGoXXMMgx22UI05Y9YA7MATiKtu_MUa7kDfFI_Y4NVcGofO5WQVHi-8bBT6db-1qoIMub9Yi_bA1r4HJPbECnHqQ5tCdhkqXJQixa5TXEnx2IKeJxGJtqINiFRJ6TGpVKeklPhl-KUm5qmBVvBeS7q0EGs8ntFNFwXRqe%22%2C%%22type%22%3A%222%22%%2C%%22utdid%22%3A%%22VT9WD2wvlkYDAEhQaEaQC22w%22%2C%%22_fromTBWebVC%22%3A%221%22%%7D", self.itemID];
    
    [AFNetworkHandler GETwithAFNByURL:Path completion:^(id result) {
        
        NSDictionary *dataDict = [result objectForKey:@"data"];
        
        NSDictionary *itemInfo = [dataDict objectForKey:@"itemInfoModel"];
        
        MXNewViewItemDetailModel *model = [[[MXNewViewItemDetailModel alloc] initWithDic:itemInfo] autorelease];
        
        model.seller = [dataDict objectForKey:@"seller"];
        
        
        self.tempTitleString = model.title;
        self.imagePath = model.picsPath[0];
        self.tempUrl = model.itemUrl;
        
        [self.itemArray addObject:model];
        
        self.urlStringArray = model.picsPath;
        
//        [self creatButtons];
        
        [self.tableView reloadData];
        
        
        [self creatTmallLinkButton];
        
        
        
        [self creatButtons];
        
        [self uiActivityindicatorviewEnd];
        
    }];
    
}


//************************* TableView Delegate 协议实现 *********************
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.itemArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MXNewViewItemDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (!cell) {
        cell = [[MXNewViewItemDetailTableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"reuse"];
    }
    
    cell.naviDetail = self.navigationController;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    [cell getInfo:self.itemArray[indexPath.row] Price:self.priceString];
    
    self.TmallLinkString = [self.itemArray[indexPath.row] itemUrl];
    
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 300;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)collectAction
{
    
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    NSArray* imageArray = @[[UIImage imageNamed:@"shareImage"]];
    
    if (imageArray) {
        
        [shareParams SSDKSetupShareParamsByText:@"分享内容"
                                         images:imageArray
                                            url:[NSURL URLWithString:@"http://mob.com"]
                                          title:@"分享标题"
                                           type:SSDKContentTypeImage];
        
        //进行分享
        [ShareSDK share:SSDKPlatformTypeSinaWeibo
             parameters:shareParams
         onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
             
             //             [theController showLoadingView:NO];
             //             [theController.tableView reloadData];
             
             switch (state) {
                 case SSDKResponseStateSuccess:
                 {
                     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                         message:nil
                                                                        delegate:nil
                                                               cancelButtonTitle:@"确定"
                                                               otherButtonTitles:nil];
                     [alertView show];
                     break;
                 }
                 case SSDKResponseStateFail:
                 {
                     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                         message:[NSString stringWithFormat:@"%@", error]
                                                                        delegate:nil
                                                               cancelButtonTitle:@"确定"
                                                               otherButtonTitles:nil];
                     [alertView show];
                     break;
                 }
                 case SSDKResponseStateCancel:
                 {
                     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享已取消"
                                                                         message:nil
                                                                        delegate:nil
                                                               cancelButtonTitle:@"确定"
                                                               otherButtonTitles:nil];
                     [alertView show];
                     break;
                 }
                 default:
                     break;
             }
             
         }];
    }
    
}

-(void)viewWillAppear:(BOOL)animated
{
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    
}



- (void)buyAction
{
    MXFindWebViewVC *webViewVC = [[[MXFindWebViewVC alloc] init] autorelease];
    
    webViewVC.requestString = self.TmallLinkString;
    
    webViewVC.TitleString = @"商品详情";
    
    [self.navigationController pushViewController:webViewVC animated:YES];
}

- (void)itemCollectAction:(UIButton *)collectButton
{
    DataBaseFMDB *dbManger = [[[DataBaseFMDB alloc] init] autorelease];
    
    // 创建数据库
    [dbManger createItemDataBase];
    
    // 创建表
    [dbManger creatItemDaseTable];
    
    collectButton.selected = !collectButton.selected;
    
    BOOL exists = [dbManger isItemExists:self.tempTitleString];
    
    
    if (collectButton.selected == YES) {
        [dbManger insertItemTable:self.tempTitleString ItemID:self.tempUrl imagePath:self.imagePath Price:self.priceString];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"收藏成功!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
        [alert show];
        [alert release];
        
    } else if (exists){
        //        collectButton.selected = YES;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"取消收藏" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
        [alert show];
        [alert release];
        
        [dbManger deleteItemData:self.tempTitleString];
        
    }

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
